<template>
  <div class="long-polling">
    <div class="status">
      <span class="status-indicator" :class="{ active: isPolling }"></span>
      <span class="status-text">{{ isPolling ? '长轮询中...' : '已停止' }}</span>
      <span class="mechanism">机制：服务器保持连接，有新数据才返回</span>
    </div>
    
    <div class="message-box">
      <h3>最新消息：</h3>
      <p class="message">{{ message }}</p>
      <div class="timestamp">{{ lastUpdateTime }}</div>
    </div>
    
    <div class="controls">
      <button 
        @click="togglePolling" 
        :class="{ active: isPolling }"
        class="toggle-btn"
      >
        {{ isPolling ? '停止轮询' : '开始轮询' }}
      </button>
    </div>
    
    <div class="stats">
      <div class="stat-item">
        <span class="stat-label">请求次数：</span>
        <span class="stat-value">{{ requestCount }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">连接状态：</span>
        <span class="stat-value" :class="{ connected: isPolling }">
          {{ isPolling ? '连接中' : '已断开' }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import axios from 'axios'

const message = ref('初始消息：暂无新内容')
const isPolling = ref(false)
const requestCount = ref(0)
const lastUpdateTime = ref('--')

// 发起长轮询请求（递归调用，形成循环）
const fetchLongPollingData = async () => {
  if (!isPolling.value) return // 停止轮询则退出

  try {
    const res = await axios.get('http://localhost:3000/polling/long', {
      timeout: 6000, // 超时时间需大于后端超时（5秒）
    })

    if (res.data.code === 200) {
      message.value = res.data.data.message // 有新数据则更新
      lastUpdateTime.value = new Date().toLocaleTimeString()
    }
    requestCount.value++
    
    // 无论是否有新数据，立即发起下一次请求
    setTimeout(fetchLongPollingData, 0)
  } catch (err) {
    console.error('长轮询请求失败：', err)
    message.value = '请求失败，请检查后端服务'
    // 出错后延迟重试（避免频繁报错）
    if (isPolling.value) {
      setTimeout(fetchLongPollingData, 1000)
    }
  }
}

// 启动/停止长轮询
const togglePolling = () => {
  isPolling.value = !isPolling.value
  if (isPolling.value) {
    fetchLongPollingData() // 启动循环
  }
}

// 组件挂载时启动
togglePolling()

// 组件卸载时停止
onUnmounted(() => {
  isPolling.value = false
})
</script>

<style scoped>
.long-polling {
  padding: 0;
}

.status {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #dc3545;
  transition: background-color 0.3s ease;
}

.status-indicator.active {
  background: #ffc107;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.status-text {
  font-weight: 500;
  color: #2c3e50;
}

.mechanism {
  margin-left: auto;
  font-size: 0.85rem;
  color: #666;
}

.message-box {
  margin: 20px 0;
  padding: 20px;
  background: #fff;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message-box h3 {
  color: #2c3e50;
  margin-bottom: 12px;
  font-size: 1.1rem;
}

.message {
  font-size: 1.1rem;
  color: #495057;
  margin-bottom: 8px;
  line-height: 1.5;
  min-height: 24px;
}

.timestamp {
  font-size: 0.85rem;
  color: #6c757d;
  text-align: right;
}

.controls {
  text-align: center;
  margin: 20px 0;
}

.toggle-btn {
  padding: 12px 24px;
  font-size: 1rem;
  font-weight: 500;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #6c757d;
  color: white;
  min-width: 120px;
}

.toggle-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.toggle-btn.active {
  background: linear-gradient(45deg, #ffc107, #ffb300);
}

.stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-label {
  font-size: 0.85rem;
  color: #6c757d;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
}

.stat-value.connected {
  color: #ffc107;
}

@media (max-width: 480px) {
  .stats {
    grid-template-columns: 1fr;
  }
  
  .status {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .mechanism {
    margin-left: 0;
  }
}
</style> 